package com.chaoxuan.uebt.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.chaoxuan.uebt.model.User;

public class SharedPreferencesUtils {
    public static final String TAG = "user";
    // 创建一个写入器
    private static SharedPreferences mPreferences;
    private static SharedPreferences.Editor mEditor;
    private static SharedPreferencesUtils mSharedPreferencesUtil;

    // 构造方法
    public SharedPreferencesUtils(Context context) {
        mPreferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        mEditor = mPreferences.edit();
    }

    // 单例模式
    public static SharedPreferencesUtils getInstance(Context context) {
        if (mSharedPreferencesUtil == null) {
            mSharedPreferencesUtil = new SharedPreferencesUtils(context);
        }
        return mSharedPreferencesUtil;
    }

    // 存入数据
    public void save(User value) {
        mEditor.putString(TAG, RetrofitUtils.getGson().toJson(value));
        mEditor.commit();
    }

    // 获取数据
    public User getUser() {
        String value= mPreferences.getString(TAG, "");
        if(TextUtils.isEmpty(value))return null;
       return  RetrofitUtils.getGson().fromJson(value,User.class);
    }

    // 移除数据
    public void remove() {
        mEditor.remove(TAG);
        mEditor.commit();
    }
}
